<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addPermission(1,'0')">添加权限</el-button>
        </div>

        <el-table :data="permissionList" border row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button v-if="scope.row.type===1" type="text" @click="addPermission(2,scope.row.id)">添加</el-button>
              <el-button type="text" @click="editPerHander(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="deletePerHander(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 放置一个弹层 用来编辑新增节点 -->
        <el-dialog :title="isEdit?'编辑权限点':'新增权限点'" :visible="showDialog" @close="btnCancel">
          <!-- 表单 -->
          <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="formData.name" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限标识" prop="code">
              <el-input v-model="formData.code" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限描述">
              <el-input v-model="formData.description" style="width:90%" />
            </el-form-item>
            <el-form-item label="开启">
              <el-switch
                v-model="formData.enVisible"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-form>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button size="small" type="primary" @click="enPermission">确定</el-button>
              <el-button size="small" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getPermissionList, addPermission, getPermissionDetail, updatePermission, delPermission } from '@/api/permission'
// 导入树形方法
import { tranListToTreeData } from '@/utils/index'
export default {
  name: 'Permission',
  data() {
    // 验证同级不允许出现同名的权限名称
    const validname = (rule, value, callback) => {
      // 筛选出同级的节点
      let existNameList = this.originList.filter(item => item.pid === this.formData.pid)

      // 编辑时的逻辑,需要把本身排除
      if (this.isEdit) {
        // 如果是编辑
        existNameList = this.originList.filter(item => item.pid === this.formData.pid && item.id === this.formData.id)
      }

      // 将筛选出来的同级name 组成一个新数组
      // 使用includes 方法验证是否在同一节点中
      existNameList.map(item => item.name.trim()).includes(value) ? callback(new Error(`权限名称${value}已存在`)) : callback()
    }
    // 验证权限标识在项目中是唯一
    const validCode = (rule, value, callback) => {
      // 先获取全部数据
      let existCodeList = this.originList

      // 如果是编辑,需要将本身进行排除
      if (this.isEdit) {
        existCodeList = this.originList.filter(item => item.id === this.formData.id)
      }
      existCodeList.map(item => item.code).includes(value) ? callback(new Error(`权限标识${value}已存在`)) : callback()
    }
    return {
      permissionList: [], // 接收权限数据
      showDialog: false, // 是否显示弹层
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: validname, trigger: 'blur' }

        ],
        code: [
          { required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }

        ]
      },
      isEdit: false, // 判断编辑和添加
      originList: []
    }
  },

  created() {
    this.getPermissionList()
  },
  methods: {
    async getPermissionList() {
      const res = await getPermissionList()
      this.originList = res.data.map(({ id, pid, name, code }) => ({ id, pid, name: name.trim(), code }))
      this.permissionList = tranListToTreeData(res.data, '0')
    },

    // 添加权限弹窗
    addPermission(type, pid) {
      this.isEdit = false

      this.formData.type = type
      this.formData.pid = pid

      this.showDialog = true
    },

    // 关闭弹框
    btnCancel() {
      this.formData = {
        name: '', // 名称
        code: '', // 标识
        description: '', // 描述
        type: '', // 类型 该类型 不需要显示 因为点击添加的时候已经知道类型了
        pid: '', // 因为做的是树 需要知道添加到哪个节点下了
        enVisible: '0' // 开启
      }
      // 重置form表单方法
      this.$refs.perForm.resetFields()
      this.showDialog = false
    },

    // 确定按钮
    enPermission() {
    // 验证用户是否输入了必填项
      this.$refs.perForm.validate(valid => {
        if (valid) {
          this.isEdit ? this.editPermissionSubmit() : this.addPermissionSubmit()
        }
      })
    },

    // 添加权限
    addPermissionSubmit() {
      // 兜底验证
      this.$refs.perForm.validate(async vlaid => {
        // 判断不通过直接打回
        if (!vlaid) return
        // 调用api
        const res = await addPermission(this.formData)
        // 成功后提示用户
        this.$message.success(res.message)

        // 关闭弹窗
        this.showDialog = false
        // 重新渲染页面
        this.getPermissionList()
      })
    },

    // 点击编辑按钮
    async editPerHander(id) {
      this.isEdit = true
      // 数据回显
      const res = await getPermissionDetail(id)
      this.formData = res.data
      // 打开弹窗
      this.showDialog = true
    },

    // 编辑权限
    async  editPermissionSubmit() {
      // 调用接口，传入参数，发起请求
      const res = await updatePermission(this.formData)

      // 重新获取页面数据
      this.getPermissionList()
      this.$message.success(res.message)
      this.showDialog = false
    },

    // 删除功能

    async deletePerHander(id) {
      // 确认消息
      const confirmRes = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes === 'cancel') return this.$message('您已取消删除')
      const res = await delPermission(id)

      this.$message.success(res.message)

      // 重新渲染页面
      this.getPermissionList()
    }
  }
}
</script>

<style lang="scss" scoped></style>

